<?php


namespace Framework\Foundation\Rest;

class CallResource
{
    protected $module;
    protected $resourceConverter;

    public function __construct($module)
    {
        $this->module = $module;
        $this->resourceConverter = new ResourceConverter();
    }

    public function callGetList($resource, $request)
    {
        $targetInfo = $this->resourceConverter->makeTarget('getList', $resource);
        return $this->callCommon($targetInfo, $request);
    }

    public function callGetInfo($resource, $id, $request)
    {
        $targetInfo = $this->resourceConverter->makeTarget('getInfo', $resource, $id);
        return $this->callCommon($targetInfo, $request);
    }

//    public function callAdd($resource, $request)
//    {
//        $targetInfo = $this->resourceConverter->makeTarget('getList', $resource);
//        return $this->callCommon($targetInfo, $request);
//    }
//
//    public function callEdit($resource, $id, $request)
//    {
//        $targetInfo = $this->resourceConverter->makeTarget('getList', $resource, $id);
//        return $this->callCommon($targetInfo, $request);
//    }

    public function callDelete($resource, $id, $request)
    {
        $targetInfo = $this->resourceConverter->makeTarget('delete', $resource, $id);
        return $this->callCommon($targetInfo, $request);
    }

    public function callCommon($targetInfo, $request)
    {
        $classPath = "\App\Http\Rest\\" . ucfirst($this->module);
        $className = $classPath . "\Resource\\" . $targetInfo['object'];

        if (class_exists($className)) {
            $obj = new $className;
        } else {
            $obj = new $classPath . '\DbResource';
        }

        return call_user_func([$obj, $targetInfo['action']], $targetInfo, $request);
    }
}
